from docx import Document
from docx.shared import Pt, Inches
from docx.oxml.ns import qn
from docx.oxml import parse_xml

def add_ruby_with_table(doc, base_text, ruby_text):
    # 创建一个1行1列的表格
    table = doc.add_table(rows=1, cols=1)
    table.autofit = False
    table.columns[0].width = Inches(0.5)  # 设置合适的列宽
    
    # 获取单元格 - 修正这里
    cell = table.rows[0].cells[0]  # 正确访问单元格的方式
    
    # 添加基础文本
    p = cell.add_paragraph()
    run = p.add_run(base_text)
    run.font.size = Pt(12)
    run.font.name = 'Microsoft YaHei'
    run._element.rPr.rFonts.set(qn('w:eastAsia'), 'Microsoft YaHei')
    
    # 添加ruby文本
    p = cell.add_paragraph()
    run = p.add_run(ruby_text)
    run.font.size = Pt(8)
    run.font.name = 'Microsoft YaHei'
    run._element.rPr.rFonts.set(qn('w:eastAsia'), 'Microsoft YaHei')
    
    # 设置表格无边框
    tbl_pr = cell._element.tcPr
    tc_borders = parse_xml(
        r'<w:tcBorders xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">'
        r'<w:top w:val="none" w:sz="0" w:space="0" w:color="auto"/>'
        r'<w:left w:val="none" w:sz="0" w:space="0" w:color="auto"/>'
        r'<w:bottom w:val="none" w:sz="0" w:space="0" w:color="auto"/>'
        r'<w:right w:val="none" w:sz="0" w:space="0" w:color="auto"/>'
        r'</w:tcBorders>'
    )
    tbl_pr.append(tc_borders)

# 创建文档
doc = Document()

# 添加ruby文本
add_ruby_with_table(doc, "红领巾", "少先队员")

# 保存文档
doc.save("ruby_text_table.docx")